import sys

import queue
import time

import cv2
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QRect
from PyQt5.QtGui import QPixmap, QPainter, QColor, QPen
from PyQt5.QtWidgets import QWidget

from UI.services.ai_interface import TrainInterface


DETECT_QUEUE = queue.Queue(maxsize=1)
ai_interface = TrainInterface()



class CameraSignal(QObject):
    frame = pyqtSignal(object)
    reset_label = pyqtSignal()
    failed_load_stream = pyqtSignal()
    res_json = pyqtSignal(object)


def push_frame_to_detect(frame):
    """
    将帧推入检测队列
    :param frame: 视频帧
    :param min_handle_secs: 最小处理时间，单位秒
    :return:
    """

    try:
        DETECT_QUEUE.put_nowait(frame)
    except Exception as e:
        # print("队列已满，丢弃当前帧,推理速度跟不上了")
        pass


def put_fps(frame, fps_label=True):
    global prev_time, frame_cnt, fps_interval, fps

    if fps_label:
        current_time = time.time()
        if current_time - prev_time <= fps_interval:
            frame_cnt += 1
        else:
            fps = frame_cnt / (current_time - prev_time)
            prev_time = current_time
            frame_cnt = 0
        # 在帧上显示帧率
        cv2.putText(frame, f"FPS: {int(fps)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    return frame


class VideoOverlay(QWidget):
    update_overlay = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.rectangles = []

    def paintEvent(self, event):
        size = self.parent().size()
        self.resize(size)

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制半透明红色背景层
        painter.fillRect(self.rect(), QColor(255, 0, 0, 0))  # 基础透明度30

        # 绘制动态矩形
        # print(self.rectangles) 传四个数字过来
        for rect in self.rectangles:
            rect = QRect(int(rect[0] * size.width()), int(rect[1] * size.height()), int(rect[2] * size.width()), int(rect[3] * size.height()))
            painter.setPen(QPen(QColor(255, 0, 0, 255), 1))
            painter.drawRect(rect)

    def reset_label(self):
        self.rectangles = []


class OverlayController(QThread):
    update_rect = pyqtSignal(list)

    def __init__(self, labels, confidence=0.5):
        super().__init__()
        self.active = True
        # self.rectangles = []
        self.labels = labels
        self.confidence = confidence
        self.width = -1
        self.height = -1

    def run(self):
        while self.active:

            # for rect in self.rectangles:
            #     # rect, alpha = self.rectangles[i]
            #     # new_alpha = 255
            #     # self.rectangles[i] = (rect)
            #
            #     self.update_rect.emit(QRect(int(100 * 640 / 1902), int(100 * 480 / 1048), int(200 * 640 / 1902), int(255 * 480 / 1048)))
            #     QThread.msleep(50)
            a = time.time()
            try:
                frame = DETECT_QUEUE.get_nowait()
            except Exception as e:
                QThread.msleep(10)
                continue
            else:
                is_success, buffer = cv2.imencode(".png", frame)


                # 检查操作是否成功
                if is_success:
                    rect_list = []
                    # 将编码后的图像数据转换为字节流
                    byte_stream = buffer.tobytes()
                    b = time.time()
                    print(b - a)
                    c = time.time()
                    res_json = ai_interface._object_to_json_custom_training_by_bytes_list(self.labels,
                                                                                          file_stream=byte_stream)
                    # print("res_json:", res_json, f"\n!!!!!!!!!!!!!!{self.labels}")
                    d = time.time()
                    print(f"检测耗时{d-c}")
                    if res_json.get('result'):
                        for label_dict in res_json['result']:
                            if label_dict['confidence'] < self.confidence:
                                continue
                            x1 = int(label_dict['xmin'])
                            y1 = int(label_dict['ymin'])
                            x2 = int(label_dict['xmax']) - x1
                            y2 = int(label_dict['ymax']) - y1
                            # print(label_dict["name"], label_dict["confidence"])

                            # TODO:修改比例关系
                            rect_list.append([x1 / self.width, y1 / self.height, x2 / self.width, y2 / self.height])
                        self.update_rect.emit(rect_list)

                    else:
                        self.update_rect.emit([])
                else:
                    self.update_rect.emit([])

            # QThread.sleep(2)  # 每2秒重置
            # for i in range(len(self.rectangles)):
            #     rect, _ = self.rectangles[i]
            #     self.rectangles[i] = (rect, 0)
            #     self.update_rect.emit(rect)

    def stop(self):
        self.active = False

    def set_pixel(self, width, height):
        self.width = width
        self.height = height


